#include <malloc.h>
#include "teacher.h"
/* 结构体数据存放内存区指针 */
static p_teacher teachers = NULL;
/* 结构体索引指针 */
//static p_teacher *p_teachers;
/* 当前长度 */
static int length = 0;
/* 当前最后一个的位置 */
static int position = -1;
/* 结构体的大小 */
static int t_size = sizeof(teacher);
/* 修改内存的 */
static p_teacher resize(tsize size);
/* 往最末尾添加一条记录 */
int push(p_teacher p)
{
	if(NULL == resize(t_size * (position + 2)))
	{
		return 0;
	}
	else
	{
		teachers[++position] = *p;
		return 1;
	}
}
/* 修改结构体容器内存 */
p_teacher resize(tsize size)
{
	if(size > (length * t_size))
	{
		void *temp = realloc(teachers,size);
		if(temp == NULL)
		{
			return (p_teacher)NULL;
		}
		teachers = temp;
		length = size / t_size;
		return teachers;
	}
	else
	{
		return teachers;
	}
}
/* 往指定位置添加一条记录 */
int insert(p_teacher p,tsize index)
{
	if(NULL == resize(t_size * (position + 2)) || position < 0)
	{
		return 0;
	}
	else
	{
		for(int i = ++position;i > index;i--)
		{
			teachers[i] = teachers[i - 1];
		}
		teachers[index] = *p;
		return 1;
	}
}
/* 删除指定位置的记录 */
int delete_by_index(tsize index)
{
	if(position < 0)
	{
		return 0;
	}
	else
	{
		for(int i = index;i < position;i++)
		{
			teachers[i] = teachers[i + 1];
		}
		position--;
		return 1;
	}
}
/* 根据传递的排序函数对数据进行排序 */
int sort(int (*c)(p_teacher,p_teacher))
{
	tsize temp_index = 0;
	teacher temp_teacher;
	for(int i = 0;i < position;i++)
	{
		temp_index = i;
		for(int j = i + 1;j <= position;j++)
		{
			if(c(teachers + temp_index,teachers + j) > 0)
			{
				temp_index = j;
			}
		}
		if(temp_index != i)
		{
			temp_teacher = teachers[temp_index];
			teachers[temp_index] = teachers[i];
			teachers[i] = temp_teacher;
		}
	}
}
/* 输出列表所有的记录 */
void print_all()
{
	printf("id\tname\tsubject\n");
	for(int i = 0;i <= position;i++)
	{
		printf("%d\t%s\t%s\n",teachers[i].id,teachers[i].name,teachers[i].subject);
	}
}
/* 清空现有的记录 */
void clean_teachers()
{
	free(teachers);
	teachers = NULL;
	length = 0;
	position = -1;
}
